class Incident < ActiveRecord::Base
  belongs_to :machines
  require 'net/smtp'
  def self.getIncidentByMachine(id_machine)
    @incidents = Incident.find(:all, :conditions => {:machine_id => id_machine, :date_resolution => nil})
    if !@incidents.empty?
       return true
    else
      return false
    end    
  end
  
  def self.getIncidentBySalle(id_salle)
    @machines = Machine.find(:all, :conditions => {:salle_id => id_salle})
    incidents = false
    for i in 0..@machines.count-1 
      if getIncidentByMachine(@machines[i].id)
        incidents = true
      end
    end
    return incidents
  end
  
  
  def self.resolve_inc(id,incident)
    @incidents = Incident.find(:all, :conditions => {:machine_id => id,:type_incident_id =>incident})
    @incidents.each do |inc|
      inc.update_attributes(:date_resolution => Time.new)
    end
  end
  
  def self.gererIncidentPing(id_machine, estResolu)
    @incident = Incident.find(:first, :conditions => {:machine_id => id_machine,:type_incident_id =>'3', :date_resolution => nil})
    puts @incident
    if @incident
      if estResolu == true
        puts "Incident ping résolu"
        @incident.update_attributes(:date_resolution => Time.new)
      else
        puts "MAJ ping incident"
        @incident.update_attributes(:updated_at => Time.new, :date_detection => Time.new)
      end
    elsif estResolu != true
      puts "Nouvelle incident sur le ping"
      @incident = Incident.new(:machine_id => id_machine, :type_incident_id =>'3', :date_detection => Time.new)
      @incident.save
    end
  end
  

  def self.sendmail(who,type)
    begin
    Net::SMTP.start('smtp.sfr.fr', 25) do |smtp|
    
        smtp.open_message_stream('nebunamirax@free.fr', 'max.beaurain@gmail.com') do |f|
    
          f.puts 'From: noreply@projetbliss.com'
    
          f.puts 'To: nebunamirax@hotmail.com'
    
          f.puts 'Subject: ['+who+']: '+ type
    
          f.puts 'Ceci est un message d\'alerte automatique suite à un incident. 
          Merci de ne pas répondre.
          
          Allez sur http://localhost:3000/incidents pour plus d\'informations'
    
        end
    
    end
    rescue
    puts "impossible d'envoyer le mail, verifier la connectivité réseau"
    end
  end
  
  
  
end
